package com.scau.service.impl;

import com.scau.dao.EWalletMapper;
import com.scau.dao.OrderItemMapper;
import com.scau.dao.PaymentFlowMapper;
import com.scau.dto.CashReFrom;
import com.scau.dto.ConstantClass;
import com.scau.dto.Order;
import com.scau.dto.PayForm;
import com.scau.exception.GoodsStockException;
import com.scau.pojo.*;
import com.scau.service.IEWalletService;
import com.scau.service.IGoodsService;
import com.scau.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class EWalletServiceImpl implements IEWalletService {
    @Autowired
    EWalletMapper eWalletMapper;
    @Autowired
    IOrderService orderService;
    @Autowired
    PaymentFlowMapper paymentFlowMapper;
    @Autowired
    IGoodsService goodsService;

    @Override
    public void addWallet(EWallet eWallet) {
        eWalletMapper.insert(eWallet);
    }

    @Override
    public EWallet getWallet(String payid) {
        EWallet eWallet = eWalletMapper.selectByPrimaryKey(payid);
        return eWallet;
    }

    @Override
    public int updateWallet(EWallet eWallet) {
         return eWalletMapper.updateByPrimaryKeySelective(eWallet);
    }

    private double count(List<Order> orders){
        double sum = 0;
        for(int i = 0; i < orders.size(); i++) {
            OrderItem orderItem = orders.get(i).getOrderItem();
            int num = orderItem.getGoodsQty();
            //计算总金额
            double price = orders.get(i).getPrice();
            double temp = num * price;
            sum += temp;
            System.out.println("sum = " + sum);
        }
        return sum;
    }

    @Override
    public String pay(PayForm payForm) throws GoodsStockException {

        //钱包登录
        String payId = payForm.getWallet().getPayId();
        String password = payForm.getWallet().getPassword();
        EWallet eWallet = eWalletMapper.selectByPrimaryKey(payId);
        if (eWallet == null) {
            return "error";
        }else if(!password.equals(eWallet.getPassword()))
            return "password error";

        //判断余额是否 >= 总金额
        List<Order> orders = payForm.getOrders();
        double sum = count(orders);
        Double balance = eWallet.getBalance();
        if(balance >= sum){
            //支付
            eWallet.setBalance(balance-sum);
            System.out.println("支付了 " + sum);
            System.out.println("金额从 " + balance +" 变成 " + (balance - sum) );
            eWalletMapper.updateByPrimaryKeySelective(eWallet);
        }else {
            eWalletMapper.updateByPrimaryKey(eWallet);
            return "余额不足";
        }


        for(int i = 0; i < orders.size(); i++) {
            OrderItem orderItem = orders.get(i).getOrderItem();
            System.out.println(i + "  减库存");
            //减库存
            String goodsId = orderItem.getGoodsId();
            Integer goodsQty = orderItem.getGoodsQty();
            goodsService.updateBrandGoodsStock(goodsId,goodsQty, ConstantClass.REDUCE_GOODS);

            //插入流水信息
            PaymentFlow paymentFlow = new PaymentFlow();
            paymentFlow.setId(orderItem.getId());
            paymentFlow.setFromPayId(orderItem.getBuyerName());
            paymentFlow.setToPayId(orderItem.getSellerName());
            paymentFlow.setType("3");
            double total = orderItem.getGoodsQty() * orders.get(i).getPrice();
            paymentFlow.setAmountMoney(total);
            Date date = new Date();
            paymentFlow.setPayDate(date);
            paymentFlow.setStatus("2"); //已支付 代发货
            paymentFlowMapper.insert(paymentFlow);

            //更新orderItem状态
            orderItem.setStatus(2);
            orderItem.setCreateDate(date);
            orderService.updateOrderItem(orderItem);
        }
        return "支付成功";
    }

    @Override
    public List<Order> ListByBuyer(String buyer_name) {

        List<OrderItem> OrderItems = orderService.getBuyerOrderItems(buyer_name);
//        System.out.println(OrderItems);

        List<Order> orders = new ArrayList<>();
        for(int i = 0; i < OrderItems.size(); i++){
            String goodsId = OrderItems.get(i).getGoodsId();
            Goods goods = goodsService.getBrandGoods(goodsId);
            double price = goods.getGoodsPrice();
            Order order = new Order(OrderItems.get(i), price);
            orders.add(order);
        }
        return orders;
    }

    @Override
    public List<OrderItem> ListBySeller(String seller_name) {
        List<OrderItem> orders = orderService.getBrandOrderItems(seller_name);
        return orders;
    }

    @Override
    public EWallet getWalletByUsername(String username) {
        EWalletExample example = new EWalletExample();
        example.createCriteria().andUsernameEqualTo(username);
        List<EWallet> eWallet = eWalletMapper.selectByExample(example);
        eWallet.get(0).setPassword(null);
        return eWallet.get(0);
    }

    @Override
    public List<PaymentFlow> getPaymentFlowByFromId(String username) {
        EWallet wallet = getWalletByUsername(username);
        String FromId = wallet.getPayId();
        PaymentFlowExample example = new PaymentFlowExample();
        example.createCriteria().andFromPayIdEqualTo(FromId);
        List<PaymentFlow> paymentFlows = paymentFlowMapper.selectByExample(example);
        return paymentFlows;
    }


    @Override
    public List<PaymentFlow> getPaymentFlowByToId(String username) {
        EWallet wallet = getWalletByUsername(username);
        String ToId = wallet.getPayId();
        PaymentFlowExample example = new PaymentFlowExample();
        example.createCriteria().andToPayIdEqualTo(ToId);
        List<PaymentFlow> paymentFlows = paymentFlowMapper.selectByExample(example);
        return paymentFlows;
    }

    @Override
    public int CashOutOrRechange(CashReFrom cashReFrom, int flag) {
        //检验密码
        String walletId = cashReFrom.getPayId();
        String password = cashReFrom.getPassword();
        EWallet temp = eWalletMapper.selectByPrimaryKey(walletId);
        if(!temp.getPassword().equals(password))  return 0;

        //记录流水
        double mount = cashReFrom.getMount();
        PaymentFlow paymentFlow = new PaymentFlow();
        //生成唯一标识
        String id = UUID.randomUUID().toString().replace("-","");
        paymentFlow.setId(id);
        paymentFlow.setAmountMoney(mount);
        paymentFlow.setStatus("0");
        paymentFlow.setPayDate(new Date());
        if(flag == 1){
            //提现
            paymentFlow.setType("2");
            paymentFlow.setFromPayId("platform");
            paymentFlow.setToPayId(walletId);
        } else{
            //充值
            paymentFlow.setType("1");
            paymentFlow.setFromPayId(walletId);
            paymentFlow.setToPayId("platform");
        }
        int result = paymentFlowMapper.insert(paymentFlow);
        return  result;
    }

    @Override
    public void CancelOreder() {
        //钱包身份验证

        //流水记录更改

        //钱包余额改变

        //库存更改


    }

    //添加流水
    @Override
    public void addPaymentFlow(PaymentFlow paymentFlow) {
        paymentFlowMapper.insert(paymentFlow);
    }

    //
    @Override
    public int CashOutOrRechangePass(String id,int flag) {
        PaymentFlow paymentFlow = paymentFlowMapper.selectByPrimaryKey(id);
        paymentFlow.setStatus("1");
        paymentFlowMapper.updateByPrimaryKey(paymentFlow);

        String fromPayId = paymentFlow.getFromPayId();
        System.out.println(fromPayId);
        String toPayId = paymentFlow.getToPayId();
        System.out.println(toPayId);
        Double amountMoney = paymentFlow.getAmountMoney();

        //品牌商提现通过
        if(flag == 2) {
            EWallet BuyerWallet = eWalletMapper.selectByPrimaryKey(toPayId);
            System.out.println("pinpaishang->"+toPayId);
            System.out.println(BuyerWallet);
            BuyerWallet.setBalance(BuyerWallet.getBalance() - amountMoney);
            return  eWalletMapper.updateByPrimaryKeySelective(BuyerWallet);
        }
        //借卖方充值通过
        else if(flag == 1){
            EWallet SellerWallet = eWalletMapper.selectByPrimaryKey(fromPayId);
            System.out.println("jiemaifang->"+fromPayId);
            System.out.println(SellerWallet);
            SellerWallet.setBalance(SellerWallet.getBalance() + amountMoney);
            return  eWalletMapper.updateByPrimaryKeySelective(SellerWallet);
        }
       return 0;

    }
}
